package com.polaris.live.ui.party.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.databinding.WidgetActscrollTopMarqueeBinding
import com.polaris.live.net.actService
import com.polaris.live.resp.back_resp.ActScrollRankRoomVo
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.widget.marqueen.MarqueeFactory

/**
 *
 * @author Created by 天晴 on 2024/7/2 14:41
 * @since 1.0.0
 **/
class ActScrollTopMarqueeView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {

    val mBinding = WidgetActscrollTopMarqueeBinding.inflate(LayoutInflater.from(context), this)
    private val marqueeFactory: TopMarqueeView
    private var mAnchorId: Long = -1 //主播Id
    private var mGiftIdBack: ((giftId: Long) -> Unit)? = null

    init {
        marqueeFactory = TopMarqueeView(context)
        mBinding.marquee.setMarqueeFactory(marqueeFactory)
        marqueeFactory.setOnItemClickListener(object : MarqueeFactory.OnItemClickListener<View, ActScrollRankRoomVo> {
            override fun onItemClick(view: View?, holder: MarqueeFactory.ViewHolder<View, ActScrollRankRoomVo>?) {
                if (mAnchorId == UserManager.getUserId()) {
                    holder?.data?.url?.let {
                        RouterUtils.routerGoto(it)
                    }
                } else {
                    if (holder?.data?.sourceType == 1L) {
                        val giftId = holder.data.objectId ?: 0
                        mGiftIdBack?.invoke(giftId)
                    }

                }
            }

        })

    }

    fun getActivitiesScroll(mViewModel: BaseViewModel, userId: Long) {
        mAnchorId = userId
        request(mViewModel)
    }

    private fun request(mViewModel: BaseViewModel) {
        mViewModel.request({ actService.getActivitiesScroll(mAnchorId) }, {
            if (it.isNotEmpty()) {
                visibility = View.VISIBLE
            }
            marqueeFactory.setData(it)

            if (it.size > 1 && !mBinding.marquee.isFlipping) {
                mBinding.marquee.startFlipping()
            }
        })
    }

    /**
     * 设置礼物Id回调，观众端使用
     */
    fun setGiftIdBackListener(back: (giftId: Long) -> Unit) {
        mGiftIdBack = back
    }

    fun reset() {
        if (mBinding.marquee.isFlipping) {
            mBinding.marquee.stopFlipping()
        }
        visibility = View.GONE
    }

}